package org.jaaksi.kottlindemo.flow

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

class TestFlowViewModel : ViewModel() {

    // 无初始值
    val liveData = MutableLiveData<Int>()

    // 必须赋初始值，会先发射一个初始值。发射相同值时只会响应一次
    val stateFlow = MutableStateFlow(0)

    // replay对新注册的发射旧的最新的几条数据，0则不发射
    // extraBufferCapacity 除replay的个数外，最多缓存几条数据
    // onBufferOverflow 当extraBufferCapacity不为0时，当超过缓存容量时采用什么策略，默认挂起，不会发射新数据会挂起
    val shareFlow = MutableSharedFlow<Int>(
        replay = 1,
        extraBufferCapacity = 2,
        onBufferOverflow = BufferOverflow.SUSPEND
    )

    fun changeValue(value: Int) {
        viewModelScope.launch {
            shareFlow.emit(value)
        }
    }

    fun changeValue2(value: Int) {
        liveData.value = value
        stateFlow.value = value
        viewModelScope.launch {
            shareFlow.emit(value)
        }
    }
}